import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { BASE_URL, JWT_LS } from '../constants'
import { IEmployee } from '../model/interfaces'

export const getTokenFromLocalStorage = () => {
    return localStorage.getItem(JWT_LS)
}

export const employeesApi = createApi({
    reducerPath: 'employeesApi',
    baseQuery: fetchBaseQuery(
        { baseUrl: `${BASE_URL}/employee`, headers: {Authorization: `Bearer ${getTokenFromLocalStorage()}`}  }),
    tagTypes:['Employees','Projects'],
    endpoints: (builder) => ({
        getEmployees: builder.query<IEmployee[], void>({
            query: () => '',
            providesTags:['Employees']
        }),
        createEmployees: builder.mutation<void, IEmployee>({
            query: (employee: IEmployee) =>  ({
                method: 'POST',
                url: '',
                body: employee
            }),
            invalidatesTags: ['Employees']
        }),
        updateEmployee: builder.mutation<void, IEmployee>({
            query: (employee: IEmployee)=> ({
                method: 'PUT',
                url: `/${employee._id}`,
                body: employee
            }),
            invalidatesTags: ['Employees','Projects']
        }),
        deleteEmployee: builder.mutation<void, string>({
            query: (id: string) => ({
                method: 'DELETE',
                url: `/${id}`
            }),
            invalidatesTags: ['Employees','Projects']
        })
    }),
})

export const {
    useGetEmployeesQuery,
    useLazyGetEmployeesQuery,
    useCreateEmployeesMutation,
    useUpdateEmployeeMutation,
    useDeleteEmployeeMutation,
} = employeesApi
